package br.ucb.rest.negocio.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;

import br.ucb.rest.negocio.AbstractBusinessObject;
import br.ucb.rest.persistencia.dao.GenericDAO;
import br.ucb.rest.persistencia.vo.FilaChamadoVO;


public class FilaChamadoBOS extends AbstractBusinessObject{

	private static FilaChamadoBOS instance;
	private Logger logger = Logger.getLogger(FilaChamadoBOS.class);
	
	private FilaChamadoBOS() {
		super();
		logger.info("Singleton instanciado com sucesso!");
	}
	
	public static FilaChamadoBOS getInstance() {
		if (instance == null) {
			instance = new FilaChamadoBOS();
		}
		return instance;
	}

	public List<FilaChamadoVO> recuperaAbertos(){
		EntityManager em = emf.createEntityManager();
		GenericDAO dao = GenericDAO.getInstance(em);
		try {
			List<FilaChamadoVO> retorno = (List<FilaChamadoVO>) dao.namedQueryListaResultados("FilaChamadoVO.recuperarAbertos", null);
			return retorno;
		}catch (Exception e) {
			logger.error("",e);
			return null;
		}finally {
			GenericDAO.liberarInstancia();
			em.close();
		}
	}
	
	public void fecharChamado(Integer chave){
		EntityManager em = emf.createEntityManager();
		GenericDAO dao = GenericDAO.getInstance(em);
		EntityTransaction transaction = em.getTransaction();
		try {
			transaction.begin();
			FilaChamadoVO vo = (FilaChamadoVO) dao.doFindByKey(FilaChamadoVO.class, chave);
			vo.setInAtendido(Boolean.TRUE);
			dao.doUpdate(vo);
			transaction.commit();
		} catch (Exception e) {
			logger.error("Erro ao atualizar registro no banco de dados!",e);
			transaction.rollback();
			return;
		}finally {
			GenericDAO.liberarInstancia();
			em.close();
		}
	}
	
	public void incluirChamado(FilaChamadoVO vo) {
		EntityManager em = emf.createEntityManager();
		GenericDAO dao = GenericDAO.getInstance(em);
		EntityTransaction transaction = em.getTransaction();
		try {
			transaction.begin();
			dao.doInsert(vo);
			transaction.commit();
		}catch (Exception e) {
			logger.error("Erro ao incluir registro no banco de dados!",e);
			transaction.rollback();
			return;
		}finally {
			GenericDAO.liberarInstancia();
			em.close();
		}
	}
}

